package com.jsm.tf.service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jsm.tf.entity.Room;
import com.jsm.tf.entity.User;
import com.jsm.tf.mapper.RoomMapper;
import com.jsm.tf.room.RoomDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RoomService {
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private UserService userService;

    public long createRoom(String roomName, Long creatorId) {
        Room room = new Room();
        room.setName(roomName);
        room.setCreatorId(creatorId);
        roomMapper.insert(room);
        return room.getId();
    }

    public List<RoomDTO> listRoom(int page, int pageSize) {

        Example example = Example.builder(Room.class).orderByAsc("id").build();
        PageHelper.startPage(page, pageSize);
        List<Room> rooms = roomMapper.selectByExample(example);
        List<User> userList = userService.listByIds(rooms.stream().map(r -> r.getCreatorId()).collect(Collectors.toList()));
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(u -> u.getId(), u -> u, (u1, u2) -> u2));
        List<RoomDTO> roomDTOList = Lists.newArrayList();
        for (Room room : rooms) {
            RoomDTO roomDTO = new RoomDTO();
            roomDTO.setName(room.getName());
            roomDTO.setId(room.getId());
            roomDTO.setCreatorNickName(userMap.get(room.getCreatorId()).getNickname());
            roomDTO.setCreatorId(room.getCreatorId());
            roomDTOList.add(roomDTO);
        }
        return roomDTOList;
    }
    public RoomDTO getById(long roomId) {
        Room room = roomMapper.selectByPrimaryKey(roomId);
        RoomDTO roomDTO = new RoomDTO();
        roomDTO.setName(room.getName());
        roomDTO.setId(room.getId());
        roomDTO.setCreatorId(room.getCreatorId());
        return roomDTO;
    }
}
